$(document).ready(function () {
    /**
     * home carousel
     */
    var swiper0 = new Swiper("#swiper-top", {
        slidersPerViwe: 1,
        spaceBetween: 30,
        autoplay: true,
        loop: true,
        effect: 'fade',
        pagination: {
            el: "#swiper-top-pag",
            clickable: true
        }
    })

    var swiper1 = new Swiper("#home-swiper-1", {
        slidesPerView: 6,
        spaceBetween: 20,
        loop: true,
        autoplay: {
            delay: 2000,
            disableOnInteraction: false,
        },
        autoplayDisableOnInteraction: false,
        navigation: {
            nextEl: "#home-swiper-1-button-next",
            prevEl: "#home-swiper-1-button-prev"
        }
    });

    var swiper2 = new Swiper("#home-swiper-2", {
        slidesPerView: 2,
        spaceBetween: 20,
        loop: true,
        autoplay: {
            delay: 2000,
            disableOnInteraction: false,
        },
        autoplayDisableOnInteraction: false,
        navigation: {
            nextEl: "#home-swiper-2-button-next",
            prevEl: "#home-swiper-2-button-prev"
        }
    });

    var swiper3 = new Swiper("#home-swiper-3", {
        slidesPerView: 3,
        spaceBetween: 20,
        loop: true,
        navigation: {
            nextEl: "#home-swiper-3-button-next",
            prevEl: "#home-swiper-3-button-prev"
        }
    });
    var swiper5 = new Swiper("#home-swiper-5", {
        slidesPerView: 2,
        spaceBetween: 20,
        loop: true,
        navigation: {
            nextEl: "#home-swiper-5-button-next",
            prevEl: "#home-swiper-5-button-prev"
        }
    });

    var swiper4 = new Swiper("#party-build-swiper", {
        spaceBetween: 30,
        loop: true,
        pagination: {
            el: '#party-build-swiper-pagination',
            clickable: true
            // renderBullet: function () {
            //   return '<span class="party-build__swiper-page"></span>';
            // }
        }
    });

    var swiper5 = new Swiper("#home-swiper-4", {
        slidesPerView: 6,
        spaceBetween: 0,
        freeMode: true,
        navigation: {
            nextEl: "#home-swiper-4-button-next",
            prevEl: "#home-swiper-4-button-prev"
        }
    });
    var swiper6 = new Swiper("#home-swiper-6", {
        slidesPerView: 2,
        spaceBetween: 0,
        loop: true,
        navigation: {
            nextEl: "#home-swiper-6-button-next",
            prevEl: "#home-swiper-6-button-prev"
        }
    });
    /**
     * home department
     */
    var depart = $("#home-depart__card");
    var departBanner = $('#home-depart__banner')

    // init
    depart.find('.department__tab[cid=1]').addClass('active');
    depart.find('.home-depart__list[cid=1]').show();
    var firChild = depart.find('.home-depart__list[cid=1]').find('.department__list-item')[0];
    $(firChild).addClass('active');
    $(departBanner.find('.home-depart__bg')[0]).addClass('active');

    // action
    depart.find('.department__tab').click(function () {
        var cid = $(this).attr('cid');
        depart.find('.department__tab').removeClass('active');
        $(this).addClass('active');
        depart.find('.home-depart__list').hide();
        depart.find('.home-depart__list[cid=' + cid + ']').show();
        var firChild = depart.find('.home-depart__list[cid=' + cid + ']').find('.home-depart__item-wrapper')[0];
        $(firChild).find('.department__list-item').trigger('mouseenter');
    });

    depart.find('.department__list-item').mouseenter(function () {
        depart.find('.department__list-item').removeClass('active');
        $(this).addClass('active');
        var cid = $(this).attr('cid');
        departBanner.find('.home-depart__bg').removeClass('active');
        departBanner.find('.home-depart__bg[cid=' + cid + '][pid=' + $(this).attr('pid') + ']').addClass('active');
    });

    //判断列表
    for (var i = 0; i < $('.arcticlist-left-list li').length; i++) {
        if ($('.arcticlist-left-list li a:eq(' + i + ')').html() == $('.header-title h3').html()) {
            $('.arcticlist-left-list ul li:eq(' + i + ')').addClass('active');
        }
    }
    $(".pagination__hidden").css("display", "none");
    $(".page_zs7y__form").css("display", "none");
    if ($(".pagination").length > 0) {
        $(".page_zs7y__form").css("display", "inline-block");
    }
    // $('a').on('click touchend', function(e) {
    //     var el = $(this);
    //     var link = el.attr('href');
    //     window.location = link;
    // });
    document.body.addEventListener('touchstart', function () {
    });

    // 服务建议

    function adviseFormValidate() {
        if (this.value === '') {
            if ($(this).hasClass('.advise-form__captcha')) $('.help-captcha').html('请输入验证码')
            $(this).parent('.form-group').addClass('has-error');
            return false
        } else {
            if ($(this).hasClass('advise-form__phone') && !/^1\d{10,10}$/.test(this.value)) {
                $(this).parent('.form-group').addClass('has-error');
                return false
            } else {
                $(this).parent('.form-group').removeClass('has-error');
                return true
            }
        }
    }

    function formCanSubmit() {
        var arr = [];
        $('#advise-form').find('.form-control').map(function () {
            if (this.value === '') {
                $(this).parent('.form-group').addClass('has-error');
                arr.push(false);
                return false
            } else {
                if ($(this).hasClass('advise-form__phone') && !/^1\d{10,10}$/.test(this.value)) {
                    $(this).parent('.form-group').addClass('has-error');
                    arr.push(false);
                    return false
                } else {
                    $(this).parent('.form-group').removeClass('has-error');
                    arr.push(true);
                    return false
                }
            }
        });
        //console.log(arr)
        return arr.every(function (value) {
            if (value) {
                return true
            } else {
                return false
            }
        })
    }

    function makeAdviseData() {
        var
            form = $('#advise-form'),
            name = $(form.find('.advise-form__name'))[0].value,
            phone = $(form.find('.advise-form__phone'))[0].value,
            title = $(form.find('.advise-form__title'))[0].value,
            body = $(form.find('.advise-form__content'))[0].value;
            captcha = $(form.find('.advise-form__captcha'))[0].value;
        return {
            "data": {
                "type": "suggestion--suggestion",
                "attributes": {
                    "title": title,
                    "suggestion": {
                        "value": body,
                        "format": "plain_text"
                    },
                    "contact_name": name,
                    "contact_phone": phone
                },
                "captcha": captcha
            }
        }
    }

    $('#advise-form').find('.form-control').blur(adviseFormValidate);

    var captcha_url = $("#the_captcha_url").val()
    $('#advise-form').find('.advise-form__submit').click(function (e) {
        e.preventDefault();
        if (formCanSubmit()) {
            var form = $('#advise-form')
            $('.advise-form__submit').prop('disabled', true)
            $.ajax({
                url: captcha_url + 'captcha/check',
                type: 'GET',
                data: {
                    'captcha': $(form.find('.advise-form__captcha'))[0].value
                },
                dataType: 'json',
                success: function(data) {
                    if (typeof(data)=='number') {
                        alert('提交过于频繁')
                        return
                    }
                    else if (data) {
                        $('.help-captcha').html('请输入验证码')
                        $('.help-captcha').parent('.form-group').removeClass('has-error')
                        $.ajax({
                            url: captcha_url + 'captcha/add_suggestion',
                            type: 'POST',
                            data: { 'data' : JSON.stringify(makeAdviseData())},
                            success: function (data) {
                                if (data=='服务建议提交成功') {
                                    $('#advise-form').find('.advise-form__reset').trigger('click');
                                    alert('提交成功')
                                    captcha_change()
                                } else {
                                    alert('提交失败')
                                }
                            }
                        })
                    } else {
                        $('.help-captcha').html('验证码错误')
                        $('.help-captcha').parent('.form-group').addClass('has-error')
                        captcha_change()
                    }
                },
                error: function() {
                },
                complete: function(xhr, status) {
                    $('.advise-form__submit').prop('disabled', false)
                }
            })
        } else {
            return false
        }
    })
    $(".info_name").click(function () {
        var name = $(this).html();
        var id = '';
        var data = $.ajax({
            url: 'http://www.sysush.com/dp/api/doctors?page[limit]=1000&fields[doctor]=name',
            type: 'GET',
            dataType: 'JSON',
            processData: false,
            success: function (data) {
                for (var i = 0; i < data.data['length']; i++) {
                    if (data['data'][i]['attributes']['name'] == name) {
                        id = data['data'][i]['id'];
                        window.location.href = "../department/department_doctor_detail?id=" + id + "";
                    }
                }

            }
        })
    })
    $("body").on("click", ".jhover", function () {
        var cid = $(this).attr("value");
        if ($(this).attr('data') == 'department') {
            window.location.href = "../department/department?cid=" + cid + "";
        }
        else if ($(this).attr('data') == 'doctor') {
            window.location.href = "../department/department_doctor_detail?id=" + cid + "";
        }
    })
    $(".baidu_line").searchSuggest({
        url: 'http://www.sysush.com/dp/api/departments?fields[department]=name',
        /*优先从url ajax 请求 json 帮助数据，注意最后一个参数为关键字请求参数*/
        /*如果从 url 获取数据，并且需要跨域，则该参数必须设置*/
        json: {
            'data': [{
                'id': '0',
                'word': 'baidu',
                'description': ''
            }, {
                'id': '1',
                'word': 'lzw.me',
                'description': ''
            }, {
                'id': '2',
                'word': 'w1.lzw.me',
                'description': ''
            }, {
                'id': '3',
                'word': 'g.lzw.me',
                'description': ''
            }, {
                'id': '4',
                'word': 'seo.lzw.me',
                'description': ''
            }],
            'defaults': 'http://lzw.me'
        },
        /*提示框的宽度，缺省为输入框的宽度相同*/
        topoffset: 16,
        /*提示框与输入框的距离，缺省为5*/
        style: 'line',
        // cssFile: '..static/css/search-suggest.css',
        processData: function (json) { // url 获取数据时，对数据的处理，作为 getData 的回调函数
            if (!json || json.length == 0) return false;
            var jsonStr = "{'data':[";
            for (var i = json.length - 1; i >= 0; i--) {
                if (json[i]) {
                    jsonStr += "{'id':'" + json[i]['id'] + "','type':'department','word':'" + json[i]['attributes']['name'] + "', 'description': ''},";
                }
            }
            jsonStr += "],'defaults':'baidu'}";

            //字符串转化为 js 对象
            return json = (new Function("return " + jsonStr))();
        },
        getData: function (word, parent, callback) { //数据获取方法

            if (!word) return;
            $.ajax({
                type: 'GET',
                /*data: "word=" + word,*/
                url: 'http://www.sysush.com/dp/api/departments?fields[department]=name',
                //'http://suggest.taobao.com/sug?code=utf-8&extras=1&q='+word+'&callback=?'
                dataType: 'json',
                timeout: 3000,
                success: function (data) {
                    var j = 0;
                    for (var i in data['data']) {
                        if (data['data'][i]['attributes']['name'].indexOf(word) != -1) {
                            // console.log(data['data'][i]['attributes']['name']);
                        } else {
                            delete data['data'][i];
                        }
                    }
                    callback(parent, data['data']);
                },
                error: function (data) {
                    callback(parent, data['data']);
                }
            });
        }

    });
    $(".doctor_line").searchSuggest({
        url: 'http://www.sysush.com/dp/api/doctors?page[limit]=1000&fields[doctor]=name',
        /*优先从url ajax 请求 json 帮助数据，注意最后一个参数为关键字请求参数*/
        /*如果从 url 获取数据，并且需要跨域，则该参数必须设置*/
        json: {
            'data': [{
                'id': '0',
                'word': 'baidu',
                'description': ''
            }, {
                'id': '1',
                'word': 'lzw.me',
                'description': ''
            }, {
                'id': '2',
                'word': 'w1.lzw.me',
                'description': ''
            }, {
                'id': '3',
                'word': 'g.lzw.me',
                'description': ''
            }, {
                'id': '4',
                'word': 'seo.lzw.me',
                'description': ''
            }],
            'defaults': 'http://lzw.me'
        },
        /*提示框的宽度，缺省为输入框的宽度相同*/
        topoffset: 16,
        /*提示框与输入框的距离，缺省为5*/
        style: 'line',
        // cssFile: '..static/css/search-suggest.css',
        processData: function (json) { // url 获取数据时，对数据的处理，作为 getData 的回调函数
            if (!json || json.length == 0) return false;
            var jsonStr = "{'data':[";
            for (var i = json.length - 1; i >= 0; i--) {
                if (json[i]) {
                    jsonStr += "{'id':'" + json[i]['id'] + "','type':'doctor','word':'" + json[i]['attributes']['name'] + "', 'description': ''},";
                }
            }
            jsonStr += "],'defaults':'baidu'}";

            //字符串转化为 js 对象
            return json = (new Function("return " + jsonStr))();
        },
        getData: function (word, parent, callback) { //数据获取方法

            if (!word) return;
            $.ajax({
                type: 'GET',
                /*data: "word=" + word,*/
                url: 'http://www.sysush.com/dp/api/doctors?page[limit]=1000&fields[doctor]=name',
                //'http://suggest.taobao.com/sug?code=utf-8&extras=1&q='+word+'&callback=?'
                dataType: 'json',
                timeout: 3000,
                success: function (data) {
                    var j = 0;
                    for (var i in data['data']) {
                        if (data['data'][i]['attributes']['name'].indexOf(word) != -1) {
                            // console.log(data['data'][i]['attributes']['name']);
                        } else {
                            delete data['data'][i];
                        }
                    }
                    callback(parent, data['data']);
                },
                error: function (data) {
                    callback(parent, data['data']);
                }
            });
        }

    });
    $(".index-nav").click(function () {
        if ($(".dropdown").hasClass("open")) {
            $(".dropdown-menu").hide(0);
        }
        else {
            $(".dropdown-menu").show(200);
        }
    })

});
